package com.zengqingfa.producerconsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @fileName: ConsumerProducerWithBlockingQueue
 * @author: zengqingfa
 * @date: 2022/12/14 16:34
 * @description:
 */
public class ConsumerProducerWithBlockingQueue {

    public static void main(String[] args) {
        ConsumerProducerWithBlockingQueue test1 = new ConsumerProducerWithBlockingQueue();
        //生产者和消费者对应的队列
        BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(10);
        Producer producer = test1.new Producer(blockingQueue);
        Consumer consumer = test1.new Consumer(blockingQueue);
        producer.start();
        consumer.start();
    }

    class Consumer extends Thread {

        private BlockingQueue<Object> queue;

        public Consumer(BlockingQueue<Object> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 100; i++) {
                    System.out.println("取出队列数据：" + queue.take() + ",仓库还有：" + queue.size());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    class Producer extends Thread {

        private BlockingQueue<Object> queue;

        public Producer(BlockingQueue<Object> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 100; i++) {
                    System.out.println("生产者放入队列：" + i);
                    queue.put(i);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
